<!--
 * @Description:
 * @Version: 1.0
 * @Author: liguansheng
 * @Date: 2022-08-03 09:40:33
 * @LastEditors: liguansheng liguansheng
 * @LastEditTime: 2023-04-11 16:42:45
-->
<template>
  <div>
    <div
      class="buttonList"
      v-if="
        props.buttonConfigs.filter(
          (e) => !e.isShow || (e.isShow && e.isShow(props.rowData)),
        ).length <= props.maxNumber
      "
    >
      <el-button
        v-for="config in buttonList"
        :key="config.eventName"
        :type="config.type"
        :link="config.link"
        @click="handleEvent(config)"
      >
        {{ config.name }}
      </el-button>
    </div>
    <el-dropdown @command="handleCommand" v-else>
      <el-button type="primary" link>
        操作
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="config in buttonList"
            :key="config.eventName"
            :command="config.eventName"
          >
            {{ config.name }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { computed, PropType } from 'vue'

import { IButtonConfig } from './type'

const props = defineProps({
  rowData: {
    type: Object as any,
    required: true,
  },
  maxNumber: {
    type: Number,
    default: 2,
  },
  buttonConfigs: {
    type: Array as PropType<IButtonConfig[]>,
    required: true,
  },
})

interface EmitsType {
  (e: 'event', eventName: string): void
}
const emit = defineEmits<EmitsType>()

const handleEvent = async (config: IButtonConfig) => {
  try {
    if (config.isConfirm) {
      await ElMessageBox.confirm(
        config.confirmMessage || `${config.name}，是否继续？`,
        config.confirmTitle || '提示',
        config.confirmConfig || {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        },
      )
    }
    emit('event', config.eventName)
  } catch (error) {
    console.log(error)
  }
}

const handleCommand = (eventName: string) => {
  const config = props.buttonConfigs.find((e) => e.eventName === eventName)
  if (!config) return
  handleEvent(config)
}

const buttonList = computed(() => {
  return props.buttonConfigs.filter(
    (config) => !config.isShow || config.isShow(props.rowData),
  )
})
</script>

<style scoped lang="scss"></style>
